import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { orderAPI } from '../api'

export const useOrderStore = defineStore('order', () => {
  const orders = ref([])
  const loading = ref(false)
  const error = ref(null)
  
  const fetchOrders = async () => {
    loading.value = true
    error.value = null
    try {
      const response = await orderAPI.getOrders()
      orders.value = response.data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
    } catch (err) {
      error.value = err.message
      console.error('获取订单列表失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  const createOrder = async (orderData) => {
    try {
      const order = {
        ...orderData,
        total: orderData.totalPrice, // 将totalPrice转换为total
        status: 'pending',
        createdAt: new Date().toISOString(),
        orderNumber: 'ORD' + Date.now().toString().slice(-8)
      }
      // 删除totalPrice字段，避免数据不一致
      delete order.totalPrice
      
      const response = await orderAPI.createOrder(order)
      orders.value.unshift(response.data)
      return response.data
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const updateOrderStatus = async (orderId, status) => {
    try {
      const response = await orderAPI.updateOrderStatus(orderId, status)
      const index = orders.value.findIndex(order => order.id === orderId)
      if (index !== -1) {
        orders.value[index] = response.data
      }
      return response.data
    } catch (err) {
      error.value = err.message
      throw err
    }
  }
  
  const getOrderById = (orderId) => {
    return orders.value.find(order => order.id === orderId)
  }
  
  const getPendingOrders = computed(() => {
    return orders.value.filter(order => order.status === 'pending')
  })
  
  const getCompletedOrders = computed(() => {
    return orders.value.filter(order => order.status === 'completed')
  })
  
  return {
    orders,
    loading,
    error,
    fetchOrders,
    createOrder,
    updateOrderStatus,
    getOrderById,
    getPendingOrders,
    getCompletedOrders
  }
})